package com.lee.member.strategy.impl;

import com.alibaba.fastjson.JSONObject;
import com.lee.http.HttpClientUtils;
import com.lee.member.config.UnionLoginConfig;
import com.lee.member.entity.MemberUser;
import com.lee.member.entity.UnionLogin;
import com.lee.member.mapper.MemberUserMapper;
import com.lee.member.strategy.UnionLoginStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 根据此http://120f24c4.ngrok.io/unionLogin?publicId=login_weixin拿到授权请求地址
 * 微信请在微信开发者工具中测试。获取到openTokenId。
 * 根据openTokenId进行登录。如果没有绑定。返回openId和publicId。根据实际业务进行注册或者已有绑定
 * @author zfl_a
 * @date 2020/4/5
 * @project login-authorization-parent
 */
@Component
public class WeiXinUnionLoginStrategy implements UnionLoginStrategy {

    @Autowired
    private UnionLoginConfig unionLoginConfig ;
    @Autowired
    private MemberUserMapper memberUserMapper;

    /**
     * 联合登录回调接口
     * @param request
     * @param unionLogin
     * @return
     */
    @Override
    public String unionLoginCallback(HttpServletRequest request, UnionLogin unionLogin) {

        String accessToken = unionLoginConfig.getWx().getAccessToken();

        String code = request.getParameter("code");
        if (StringUtils.isEmpty(code)) {
            return null;
        }
        //获取accessToken和openId。微信是一起返回的(跟qq的不同之处)
        String getAccessTokenAddress = accessToken.
                replace("{APPID}", unionLogin.getAppId() + "").replace("{SECRET}",
                unionLogin.getAppKey()).replace("{CODE}", code);
        JSONObject accessTokenResult = HttpClientUtils.httpGet(getAccessTokenAddress);
        if (accessTokenResult == null) {
            return null;
        }
        boolean errcode = accessTokenResult.containsKey("errcode");
        if (errcode) {
            return null;
        }
        // 获取openid
        String openid = accessTokenResult.getString("openid");
        if (StringUtils.isEmpty(openid)) {
            return null;
        }
        return openid;
    }


    /**
     * 查询用户信息
     * @param openId
     * @return
     */
    @Override
    public MemberUser queryUser(String openId) {
        return memberUserMapper.selectByWxOpenId(openId);
    }
}
